/*
 * Copyright 2008-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.appengine.twitter.interfaces.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.twitter.domain.model.User;
import com.google.appengine.twitter.domain.model.UserRepository;
import com.google.appengine.twitter.security.PasswordEncoder;
import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 *
 * @author politics wang
 * @since Apr 26, 2009
 *
 */
@Singleton
public class CreateAccountServlet extends HttpServlet {

	private static final long serialVersionUID = 6535894851964589619L;

	@Inject
	private UserRepository userRepository;
	
	@Inject
	private PasswordEncoder passwordEncoder;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		
		User user = populateUser(request);
		userRepository.save(user);
		
		response.sendRedirect("/");
	}

	private User populateUser(HttpServletRequest request) {
		String email = request.getParameter("user[email]");
		boolean sendEmailNewsLetter = Boolean.valueOf(request.getParameter("user[send_email_newsletter]"));
		String password = request.getParameter("user[user_password]");
		String recpachaResponseField = request.getParameter("recaptcha_response_field");
		String screenName = request.getParameter("user[screen_name]");
		String name = request.getParameter("user[name]");
		String authenticityToken = request.getParameter("authenticity_token");
		String follow = request.getParameter("follow");
		
		return new User(email, sendEmailNewsLetter, passwordEncoder.encode(password), screenName, name);
	}

	
	
}
